package com.scap.authen.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Encryption {
	/**
	 * for md5Encrypt Data
	 * @param paData
	 * @return vaMD5Encrypt
	 */
	public String md5Encrypt(String paData) {
		String vaMD5Encrypt = "";
		MessageDigest voMd;
		try {
			voMd = MessageDigest.getInstance("MD5");
			byte[] hash;
			try {
				hash = voMd.digest(paData.getBytes("UTF-8"));
				StringBuilder voSb = new StringBuilder(2 * hash.length);
				for (byte b : hash) {
					voSb.append(String.format("%02x", b & 0xff));
				}
				vaMD5Encrypt = voSb.toString();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return vaMD5Encrypt;
	}
	/**
	 * for Encrypt Data
	 * @param paData
	 * @return vaDataEncrypt
	 */
	public String dataEncrypt(String paData) {
		String vaDataEncrypt = "";
		int count = paData.length();
		int characterId = 0;
		if (count % 2 == 0) {
			for (int i = 1; i <= paData.length(); i++) {
				characterId = paData.charAt(i - 1) + (((i + 7) % 7) * 7)
						+ (((i + 7) % 7) * 7);
				if (characterId > 126) {
					characterId = characterId - 126 + 31;
				}
				char character = (char) characterId;
				vaDataEncrypt += character;
			}
		} else {
			for (int i = 1; i <= paData.length(); i++) {
				characterId = paData.charAt(i - 1) + (((i + 7) % 7) * 7)
						+ (((i + 7) % 7) * 7);
				if (characterId > 126) {
					characterId = characterId - 126 + 31;
				}
				char character = (char) characterId;
				vaDataEncrypt += (char) (character + (((i + 3) % 3) * 3));
				vaDataEncrypt += character;
				vaDataEncrypt += (char) (character + (((i + 7) % 7) * 7));
			}
		}
		return vaDataEncrypt;
	}
	/**
	 * for Decrypt Data
	 * @param paData
	 * @return vaDataDecrypt
	 */
	public String dataDecrypt(String paData) {
		String vaDataDecrypt = "";
		String vaNewData = "";
		int count = paData.length();
		int characterId = 0;
		if (count % 2 == 0) {
			for (int i = 1; i <= paData.length(); i++) {
				characterId = paData.charAt(i - 1) - (((i + 7) % 7) * 7)
						- (((i + 7) % 7) * 7);
				if (characterId < 32) {
					characterId = characterId + 126 - 31;
				}
				char character = (char) characterId;
				vaDataDecrypt += character;
			}
		} else {
			for (int i = 1; i <= paData.length(); i += 3) {
				vaNewData += paData.charAt(i);
			}
			for (int i = 1; i <= vaNewData.length(); i++) {
				characterId = vaNewData.charAt(i - 1) - (((i + 7) % 7) * 7)
						- (((i + 7) % 7) * 7);
				if (characterId < 32) {
					characterId = characterId + 126 - 31;
				}
				char character = (char) characterId;
				vaDataDecrypt += character;
			}
		}
		return vaDataDecrypt;
	}

}
